package com.nulp.psycho.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nulp.psycho.db.dao.impl.TestDao;
import com.nulp.psycho.db.model.Answer;
import com.nulp.psycho.db.model.Question;
import com.nulp.psycho.db.model.Test;
import com.nulp.psycho.db.service.AnswerService;
import com.nulp.psycho.db.service.QuestionService;

public class TestQuestionsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int id = Integer.parseInt(request.getParameter("testId"));
		Test test = new TestDao().read(id);
		String testName = test.getName();

		request.setAttribute("testName", testName);
		List<Question> questions = new QuestionService().getAllQuestionsByTestId(id);

		List<List<Answer>> answers = new ArrayList<List<Answer>>();
		//List<List<Answer>> answers = new ArrayList<List<Answer>>();
		AnswerService ansService = new AnswerService();

		for (Question q : questions) {
			answers.add((List<Answer>) ansService.getAllAnswersByQuestionId(q.getId()));
		}
		request.setAttribute("testId", id);
		request.setAttribute("answers", answers);
		request.setAttribute("testQuestions", questions); 

		request.getRequestDispatcher("WEB-INF/pages/takeTheTest.jsp").forward(request, response);
	}

}
